import { PaginationProps, PaginationResponse } from '@/common';
import { PaginationProps as AntPaginationProps, Pagination, Table } from 'antd';
import { useLockFn, useMemoizedFn, useRequest } from 'ahooks';
import { useCallback, useState } from 'react';
import { ColumnsType } from 'antd/es/table';

export function usePaginationTable<
  TParams extends PaginationProps,
  TData extends PaginationResponse,
>(
  api: (data: TParams) => Promise<TData>,
  {
    searchText = '',
    refreshDeps = [],
    params = {},
    EmptyTip,
    rowKey = 'keyQuestionId',
    columns,
    filter,
  }: {
    searchText: string;
    refreshDeps?: any[];
    params?: Record<string, any>;
    EmptyTip?: React.JSX.Element;
    rowKey?: string;
    columns: ColumnsType<any>;
    filter: (datas: any[], searchText: string) => any[];
  },
) {
  const [page, setPage] = useState(1);
  const [pageSize, setPageSize] = useState(10);
  const [total, setTotal] = useState(0);
  const [datas, setDatas] = useState<any[]>([]);
  const [loading, setLoading] = useState(false);

  const noMore = datas.length >= total;

  const loadData = useLockFn(async (init = false) => {
    if (noMore && !init) return;
    try {
      setLoading(true);
      const res = await api({ page: page, page_size: pageSize, searchText, ...params } as TParams);
      setDatas(res?.list || []);
      setTotal(res?.total || 0);
    } catch (error) {
      console.error(error);
    } finally {
      setLoading(false);
    }
  });

  // const PaginationTable = () => {
  //   const onChange: AntPaginationProps['onChange'] = (current, pageSize) => {
  //     setPage(current);
  //     setPageSize(pageSize);
  //   };
  //   return (
  //     <div className="know-gov-table flex h-full flex-col gap-4 overflow-y-auto">
  //       <Table
  //         loading={loading}
  //         rowKey={rowKey}
  //         columns={columns}
  //         dataSource={datas}
  //         pagination={false}
  //         scroll={{ x: 'calc(700px + 50%)', y: 'calc(80vh - 10px)' }}
  //       />
  //       <div className="mb-4 ml-auto mr-10 mt-auto">
  //         <Pagination
  //           defaultCurrent={1}
  //           total={total}
  //           pageSize={pageSize}
  //           current={page}
  //           showSizeChanger
  //           onChange={onChange}
  //         />
  //       </div>
  //     </div>
  //   );
  // };

  const PaginationTable = useCallback(() => {
    const onChange: AntPaginationProps['onChange'] = (current, pageSize) => {
      setPage(current);
      setPageSize(pageSize);
    };

    return (
      <div className="know-gov-table flex h-full flex-col overflow-y-auto gap-4">
        <Table
          loading={loading}
          rowKey={rowKey}
          columns={columns}
          dataSource={datas}
          pagination={false}
          scroll={{ x: 'calc(700px + 50%)', y: 'calc(80vh - 10px)'}}
        />
        <div className="mb-4 ml-auto mr-10 mt-auto">
          <Pagination
            defaultCurrent={1}
            total={total}
            pageSize={pageSize}
            current={page}
            showSizeChanger
            onChange={onChange}
          />
        </div>
      </div>
    );
  }, [page, pageSize, datas, total, searchText, loading, rowKey, columns]);

  useRequest(
    async () => {
      await loadData(true);
    },
    {
      manual: false,
      refreshDeps: [...refreshDeps, page, pageSize],
    },
  );

  const refreshList = useMemoizedFn(() => {
    loadData(true);
  });

  return {
    PaginationTable,
    loading,
    total: Math.max(total, datas.length),
    datas,
    setDatas,
    fetchData: loadData,
    refreshList,
  };
}
